package com.example.gkcircle.utils;

import android.util.Log;

import com.example.gkcircle.library.utils.LibraryStringUtil;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

/**
 * 
 * @ClassName: HttpClientUtil
 * @Description: TODO(封装多线程的HttpClient工具)
 * @author ZhouHua
 * @date 2015年9月12日 上午11:07:53
 *
 */
public class HttpClientUtil {

	// 连接超时
	public static final int CONNECTION_TIME_OUT = 0;
	// 请求成功状态码
	public static final int HTTP_OK = 200;

	public static final int HTTP_FOUND=302;
	// UTF-8编码
	private static final String CHARSET = HTTP.UTF_8;
	// client
	private static HttpClient mHttpClientUtil;

	public static final String TAG="HttpClientUtil";

	public HttpClientUtil() {

	}

	public static synchronized HttpClient getHttpClient() {
			HttpParams params = new BasicHttpParams();
			// 设置一些基本参数
			HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
			HttpProtocolParams.setContentCharset(params, CHARSET);
			HttpProtocolParams.setUseExpectContinue(params, true);
			HttpProtocolParams.setUserAgent(params, "Mozilla/5.0(Linux;U;Android 2.2.1;en-us;Nexus One Build.FRG83) " + "AppleWebKit/553.1(KHTML,like Gecko) Version/4.0 Mobile Safari/533.1");
			// 超时设置
			/* 从连接池中取连接的超时时间 */
			ConnManagerParams.setTimeout(params, 1000 * 5);
			/* 连接超时 */
			HttpConnectionParams.setConnectionTimeout(params, 1000 * 18);
			/* 请求超时 */
			HttpConnectionParams.setSoTimeout(params, 1000 * 18);

			// 设置我们的HttpClient支持HTTP和HTTPS两种模式
			SchemeRegistry schReg = new SchemeRegistry();
			schReg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
			schReg.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));

			// 使用线程安全的连接管理来创建HttpClient
			ClientConnectionManager conMgr = new ThreadSafeClientConnManager(params, schReg);
			mHttpClientUtil = new DefaultHttpClient(conMgr, params);
		return mHttpClientUtil;
	}

	/**
	 * 
	 * @Title: get请求
	 * @Description: TODO(这里用一句话描述这个方法的作用)
	 * @param @param url
	 * @param @param cookie
	 * @param @param params//请求参数(key为header,value为param)
	 * @return RequestResult 请求结果
	 */
	public static RequestResult get(String url, String cookie, HashMap<String, String> params) {

		try {
			// 自动编码UTF-8
			HttpGet get = new HttpGet(null != params ? LibraryStringUtil.getUrl(url, params) : url);
			// cookie为null则设置默认请求头信息
			get.setHeaders(null == cookie ? getDefaultHeaders(null) : getDefaultHeaders(cookie));
			// 发送请求
			HttpClient client = getHttpClient();
			HttpResponse response = client.execute(get);
			// 判断状态码
			int statusCode=response.getStatusLine().getStatusCode();
			if (statusCode == HTTP_OK || statusCode==HTTP_FOUND) {
				HttpEntity entity = response.getEntity();
				RequestResult result = new RequestResult();
				result.setBody(EntityUtils.toString(entity, CHARSET));
				return result;
			} else {
				// 请求失败
				return null;
			}
		} catch (RuntimeException r) {
			r.printStackTrace();
			return null;
		} catch (ClientProtocolException c) {
			c.printStackTrace();
			return null;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		} finally {
			// 关闭连接并释放资源
			shutdownHttpClient();
		}
	}

	/**
	 * @Title: post
	 * @Description: TODO(post请求)
	 * @param @param url
	 * @param @param cookie
	 * @param @param param map参数名为key，参数值为value
	 */
	public static RequestResult post(String url, String cookie, HashMap<String, String> param) {

		try {
			// 设置参数,编码UTF-8
			UrlEncodedFormEntity entity = new UrlEncodedFormEntity(postParam(param), CHARSET);
			HttpPost post = new HttpPost(url);
			// cookie为null则设置默认请求头信息
			post.setHeaders(cookie == null ? getDefaultHeaders(null) : getDefaultHeaders(cookie));
			post.setEntity(entity);
			// 发送请求
			HttpClient client = getHttpClient();
			HttpResponse response = client.execute(post);
			// 判断状态码
			if (response.getStatusLine().getStatusCode() == HTTP_OK) {
				RequestResult result = new RequestResult();
				result.setBody(EntityUtils.toString(response.getEntity(), CHARSET));
				result.setCookie(cookie);
				return result;
			} else {
				// 请求失败
				return null;
			}
		} catch (RuntimeException r) {
			r.printStackTrace();
			return null;
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return null;
		} catch (ClientProtocolException e) {
			e.printStackTrace();
			return null;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		} finally {
			// 关闭连接并释放资源
			shutdownHttpClient();
		}
	}

	// 封装post请求参数
	// map 参数名为key，参数值为value
	private static List<NameValuePair> postParam(HashMap<String, String> param) {
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		Iterator<String> it = param.keySet().iterator();
		while (it.hasNext()) {
			String key = it.next();
			String value = param.get(key);
			params.add(new BasicNameValuePair(key, value));
		}
		return params;
	}

	// 在Application onLowMemory中关闭client(内存不够时关闭)
	public static void shutdownHttpClient() {
		if (null != mHttpClientUtil && null != mHttpClientUtil.getConnectionManager()) {
			mHttpClientUtil.getConnectionManager().shutdown();
			mHttpClientUtil = null;
		}
	}

	/**
	 * //TODO 默认header
	 *
	 * @return
	 */
	public static Header[] getDefaultHeaders(String cookie) {
		Header[] allHeader = new BasicHeader[null != cookie ? 3 : 2];
		allHeader[0] = new BasicHeader("Content-Type", "application/x-www-form-urlencoded");
		allHeader[1] = new BasicHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.10; rv:43.0) Gecko/20100101 Firefox/43.0");
		if (null != cookie) {
			allHeader[2] = new BasicHeader("Cookie", cookie);
		}
		return allHeader;
	}


	/**
	 * 
	 * @ClassName: RequestResult
	 * @Description: (请求结果)
	 * @author ZhouHua
	 * @date 2015年9月12日 上午11:11:12
	 *
	 */
	public static class RequestResult {



		// HTML cookie
		private String cookie;
		// HTML content
		private String body;

		private Header[] headers;

		public void setHeaders(Header[] headers) {
			this.headers = headers;
		}

		public Header[] getHeaders() {

			return headers;
		}

		public String getCookie() {
			return cookie;
		}

		public void setCookie(String cookie) {
			this.cookie = cookie;
		}

		public String getBody() {
			return body;
		}

		public void setBody(String body) {
			this.body = body;
		}

	}

}
